<?php

namespace App\Http\Controllers\Api\Web\Article;

use App\Http\Controllers\Common\ApiController;
use App\Models\Article\ArticleClassify;
use App\Models\Article\ArticleInfo;
use App\Models\Article\ArticleInfoReview;
use App\Service\ArticleClassifyService;
use App\Service\ArticleService;
use Illuminate\Http\Request;

class ArticleController extends ApiController {
    private $service;
    private $serviceArticleClassify;

    public function __construct() {
        $this->service = new ArticleService(ArticleInfo::class);
        $this->serviceArticleClassify = new ArticleClassifyService(ArticleClassify::class);
    }

    public function lst(Request $request) {

        if($request->has('articleClassify')){
            $records = $this->serviceArticleClassify->lst([])->get(['id','name']);
            return responseSuccess($records->toArray(),$records->count());
        }


        $page = $request->input('page',1);
        $pageSize = $request->input('pageSize',10);
        $classifyId = $request->input('classifyId');
        $status = $request->input('status',1);
        $conditions = compact('classifyId','status');
        $records = $this->service->lst($conditions)->paginate($pageSize,['*'],'page',$page);
        $classifies = $this->serviceArticleClassify->lst(['status'=>1])->get(['id','name']);
        return responseSuccess($records->items(),$records->total(),100000,compact('classifies'));
    }

    public function detail(Request $request) {
        $id = $request->input('id',0);
        $limit = $request->input('limit',10);
        $status = $request->input('status',1);

        $this->validate($request, ['id'=>'required|Integer|min:1']);

        if($request->has('template')){
            $record = ArticleInfoReview::where('id',$id)->first();
        }else{
            $record = $this->service->detail($id);
            if(!empty($record)){
                $record->see_num+=1;
                $record->save();
            }
        }

        //$classifies = $this->serviceArticleClassify->lst(['status'=>1])->get(['id','name']);
        //$hot = $this->service->lst(compact('status'))->limit($limit)->get();

        //return responseSuccess(empty($record)?[]:$record->toArray(),1,100000,compact('classifies','hot'));
        return responseSuccess(empty($record)?[]:$record->toArray(),1);
    }

    public function getHot(Request $request) {
        $classifyId = $request->input('classifyId');
        $limit = $request->input('limit',10);

        $this->validate($request, [
            'classifyId'=>'required'
        ],[],['classifyId'=>'资讯分类id']);

        $records = $this->service->getHot($classifyId,$limit);
        return responseSuccess($records->toArray(),$records->count());

    }
}
